from alipay import AliPay
from django.http import HttpResponseForbidden, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from apps.users.mixins import LoginRequiredJSONMixin
from config import settings
from utils.response_code import RETCODE


class PaymentView(LoginRequiredJSONMixin, View):
    def get(self, request, order_id):
        user = request.user

        # 1. 查订单
        try:
            order = OrderInfo.objects.get(
                order_id=order_id,
                user=user,
                status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']
            )
        except OrderInfo.DoesNotExist:
            return HttpResponseForbidden('订单信息错误')

        # 2. 构建支付对象（使用 settings 中的统一密钥）
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_private_key_string=settings.APP_PRIVATE_KEY,
            alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG,
        )

        # 3. 生成支付链接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=f'小鱼商城订单 {order_id}',
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 4. 拼接完整的跳转地址
        alipay_url = settings.ALIPAY_URL + "?" + order_string

        # 5. 返回支付链接
        return JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'OK',
            'alipay_url': alipay_url
        })
class PaymentStatusView(View):
    def get(self, request):
        # 获取到所有的查询字符串参数
        query_dict = request.GET
        # 将查询字符串参数的类型转换为字典类型
        data = query_dict.dict()
        # 从查询字符串参数中移除sign值,sign不参与签名验证
        signature = data.pop('sign')
        # 使用支付宝对象调用验证通知接口函数，得到一个验证结果
        # 创建支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调 url
            app_private_key_string=settings.APP_PRIVATE_KEY,
            alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG,
        )
        success = alipay.verify(data, signature)
        if success:
            # 如果验证通过，那么保存订单，并修改订单状态
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )
            OrderInfo.objects.filter(order_id=order_id,
                                     status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
            context = {
                'trade_id': trade_id
            }
            return render(request, 'pay_success.html', context)
        else:
            # 如果验证不通过，那么可以重定向到我的订单页面
            return redirect(reverse('users:myorderinfo'))

